<template>
  <el-form size="large"
    ref="mobieRef"
    :rules="rules"
    :model="form"
    class="login-content-form">
    <el-form-item class="login-animation1"
      prop="phoneNumber">
      <el-input text
        placeholder="请输入手机号"
        v-model="form.phoneNumber"
        clearable
        autocomplete="off">
        <template #prefix>
          <i class="iconfont icon-dianhua el-input__icon"></i>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item class="login-animation2"
      prop="phoneCode">
      <el-col :span="17">
        <el-input text
          placeholder="请输入验证码"
          v-model="form.phoneCode"
          clearable
          autocomplete="off">
          <template #prefix>
            <el-icon class="el-input__icon"><ele-Position /></el-icon>
          </template>
        </el-input>
      </el-col>
      <el-col :span="1"></el-col>
      <el-col :span="6">
        <el-button v-waves
          class="login-content-code"
          @click="send"
          v-show="codeData.codeShow">发送验证码</el-button>
        <el-button v-waves
          class="login-content-code"
          v-show="!codeData.codeShow"
          disabled>{{codeData.count}}s</el-button>
      </el-col>
    </el-form-item>
    <el-form-item class="login-animation3">
      <el-button type="primary"
        class="login-content-submit"
        round
        v-waves
        @click="onSignIn"
        :loading="loading.signIn"
        :disabled="loading.signIn">
        <span>登 录</span>
      </el-button>

    </el-form-item>
  </el-form>
</template>

<script setup name="loginMobile">
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { initBackEndControlRoutes } from '/@/router/backEnd';
import { RSAUtils, MD5Utils, Session, NextLoading } from '@/utils';
import { formatAxis } from '/@/utils/formatTime';
import { reactive } from 'vue';
import { PHONE_NUMBER_REG } from '@/common/cons-regular.js'
import { useSystemStore } from '@/stores/modules/store-system.js';
import { useLoginApi } from '@/api';
// 短信验证码
const { getMobileCode } = useLoginApi();

// 定义变量内容
const route = useRoute();
const router = useRouter();

const codeData = reactive({
  codeShow: true,    //按钮显示
  count: '',    //倒计时
  timer: null,    //计时器
})


let ruleForm = reactive({
  phoneNumber: '',
  phoneCode: ''
});
let loading = reactive({
  signIn: false,
});

let form = reactive({
  ...ruleForm
})

const mobieRef = ref('');
const rules = reactive({
  phoneNumber: [{ required: true, pattern: PHONE_NUMBER_REG, message: '请输入正确的手机号码！', trigger: 'blur' }],
  // phoneCode: [{ required: true, message: '请输入验证码！', trigger: 'blur' }],
})

// 获取验证码
const send = async () => {
  await mobieRef.value.validate(valid => {
    if (valid) {
      getCode();
    }
  })
}

const getCode = async () => {
  let clicktime = new Date().getTime() + 60000;   //未来60秒，这里也毫秒为单位
  // 获取数据
  let params = { phoneNumber: form.phoneNumber }
  const result = await getMobileCode(params)
  const { code, msg, data } = result
  if (code === 200) {
    timeDown(clicktime)  //请求成功则触发timeDown并将时间携带过去
    ElMessage.success(msg ?? '业务成功');
  } else {
    ElMessage.error(msg ?? '业务失败')
  }
}

const timeDown = async (time) => {
  if (!codeData.timer) {
    codeData.count = Math.ceil((JSON.parse(time) - new Date().getTime()) / 1000);  //取出计时
    codeData.codeShow = false;
    codeData.timer = setInterval(() => {
      if (codeData.count > 0) {
        codeData.count--;
      } else {
        codeData.codeShow = true;
        clearInterval(codeData.timer);  //清除计时器
        codeData.timer = null;
      }
    }, 1000)
  }
}

// 时间获取
const currentTime = computed(() => {
  return formatAxis(new Date());
});

// 登录
const onSignIn = async () => {
  await mobieRef.value.validate(valid => {
    if (valid) {
      mobileSign();
    }
  })
}

const mobileSign = async () => {
  if (form.phoneCode.length > 0) {
    /** 表单校验 */
    if (loading.signIn) return;
    loading.signIn = true;
    // 后端控制路由
    const signInData = {
      phoneNumber: form.phoneNumber,
      phoneCode: form.phoneCode,
    };
    const falg = await useSystemStore().signInMobile(signInData);
    if (!falg) {
      loading.signIn = false;
      return;
    }
    // 添加完动态路由，再进行 router 跳转，否则可能报错 No match found for location with path "/"
    const isNoPower = await initBackEndControlRoutes();
    // 执行完 initBackEndControlRoutes，再执行 signInSuccess
    signInSuccess(isNoPower);
    // 前端控制路由
  } else {
    ElMessage.error('请输入验证码！')
  }
}

// 登录成功后的跳转
const signInSuccess = (isNoPower) => {
  if (isNoPower) {
    useSystemStore().clearAllCache()
    Session.clear();
  } else {
    // 初始化登录成功时间问候语
    let currentTimeInfo = currentTime.value;
    // 登录成功，跳到转首页
    // 如果是复制粘贴的路径，非首页/登录页，那么登录成功后重定向到对应的路径中
    if (route.query?.redirect) {
      // 解密路由传递参数
      let routeParams = route.query.params
      routeParams = atob(routeParams)
      routeParams = routeParams ? JSON.parse(routeParams) : ''
      router.push({
        path: route.query?.redirect,
        query: routeParams,
      });
    } else {
      router.push('/');
    }
    // 登录成功提示
    const signInText = '欢迎回来！';
    ElMessage.success(`${currentTimeInfo}，${signInText}`);
    // 添加 loading，防止第一次进入界面时出现短暂空白
    NextLoading.start();
  }
  loading.signIn = false;
};

</script>

<style scoped lang="scss">
.login-content-form {
	margin-top: 20px;
	@for $i from 1 through 4 {
		.login-animation#{$i} {
			opacity: 0;
			animation-name: error-num;
			animation-duration: 0.5s;
			animation-fill-mode: forwards;
			animation-delay: calc($i/10) + s;
		}
	}
	.login-content-code {
		width: 95px;
		padding: 0;
		margin: 0;
	}
	.login-content-submit {
		width: 100%;
		letter-spacing: 2px;
		font-weight: 300;
		margin-top: 15px;
	}
	.login-msg {
		color: var(--el-text-color-placeholder);
	}
}
</style>
